<template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm autoClass">
        <el-form-item v-for="(item,index) in tabUserList2.colum" :key="index" :label="item.jsonValue" :prop="item.key">
            <!-- 文本 -->
            <el-input v-if="item.type=='text'" v-model="ruleForm[item.jsonKey]"></el-input>
            <!-- 数字 -->
            <el-input  @input="getnum(ruleForm[item.jsonKey],item.jsonKey)" v-if="item.type=='number'" v-model="ruleForm[item.jsonKey]"></el-input>
            <!-- 百分比 -->
            <el-input 
                :disabled="item.designFormulas&&item.designFormulas.length!=0" 
                @input="getnum(ruleForm[item.jsonKey],item.jsonKey)" 
                v-if="item.type=='bfb'" 
                v-model="ruleForm[item.jsonKey]">
                
                <template slot="append">%</template>
            </el-input>
            <!-- 下拉框 -->
            <el-select filterable v-if="item.type=='select'||item.type=='connector'" style="width: 100%;" v-model="ruleForm[item.jsonKey]" placeholder="请选择">
                <el-option
                    v-for="(citem,index) in selectOptions[item.jsonKey]"
                    :key="index"
                    :label="citem.jsonTitle"
                    :value="citem.jsonTitle">
                    </el-option>
                </el-select>
            <!-- 文件框 -->
            <el-upload
                v-if="item.type=='upload'"
                class="upload-demo"
                :action="httpUrl+get_branch+'/ht-bpmn/activiti/upload?fileType='+item.jsonValue"
                :headers="headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :on-success="(v)=>{
                    ruleForm[item.jsonKey] = v.data
                    filePath = v.data
                }"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <p class="fileInfo" :title="filePath">{{ filePath }}</p>
            </el-upload>
              <!--日期  -->
            <el-date-picker
            v-model="ruleForm[item.jsonKey]"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            v-if="item.type=='date'"
            type="date"
            placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置 </el-button>
           
        </el-form-item>
    </el-form>
</template>

<script>
import { getToken } from '@/utils/auth'
import request from '@/utils/request';
  export default {
    props:{
        formItem:{
            type:Array,
            require:true,
            default:[]
        },
        tabUserList2:{
            type:Object,
            require:true,
            default:()=>{
                return {}
            }
        }
    },  
    data() {
      return {
        bfbObjStr:[],
        selectOptions:{},
        filePath:"",
        fileList:[],
        httpUrl: process.env.VUE_APP_BASE_API,
        ruleForm: {},
        headers: {
            Authorization: 'bearer ' + getToken()
        },
        rules: {}
      };
    },
    created(){
        // console.log(this.formItem,this.tabUserList2)
        this.rules = {}
        this.ruleForm = {}
        this.tabUserList2.colum.forEach((item,index)=>{
            this.$set(this.ruleForm,item.jsonKey,'')
            if(item.type=='select'){
                this.getSelectFun(item.selectItem,item.jsonKey)
            }else if(item.type=='connector'){
                this.getconnectorList(item)
            }else if(item.type=='bfb'){
                 this.bfbObjStr.push(item)
            }
            this.rules[item.jsonKey] = [{ required: item.required, message: `请输入${item.jsonValue}`, trigger: 'change' }]
        })
    },
    methods: {
        calculateFormula(formula) {
            formula = formula.replace(/\s/g, '');
            var func = new Function('return ' + formula);
            return func();
        },
        countval(v,key){
            let keysList = this.tabUserList2.colum.map((item,index)=>{
                return item.jsonKey
            })
            let flag = false
            keysList.forEach((str,index)=>{
                if(v.includes(str)){
                    if(this.ruleForm[str]){
                        v = v.replace(str,this.ruleForm[str])
                    }else{
                        flag = true
                    }
                }
            })
            if(flag) {
                 return
            }else{
                var result = this.calculateFormula(v);
                this.$set(this.ruleForm,key,(result*100).toFixed(2))
            }
        },
        // 金额输入框
        getnum(data,attr) {
            const regex = /^\d+(\.\d+)?$/; // 正则表达式，匹配数字或小数
            if (!regex.test(data)) {
                this.$set(this.ruleForm,attr,data.replace(/[^\d.]/g, ''))
            }
            this.bfbObjStr.forEach((item,index)=>{
                if(item.designFormulas.includes(attr)){
                    this.countval(item.designFormulas,item.jsonKey)
                }
            })
        },
        getconnectorList(item){
            let obj = {
                url: '/ht-bpmn'+item.selectItem,
                method: item.method,
            }
            if(item.method=='post'){
                obj.data = item.param?JSON.parse(item.param):{}
            }
            request(obj).then((res) => {
                if(res.code==200){
                    res.data.forEach((item,index)=>{
                        item.jsonTitle = item.userRealName
                    })
                    this.$set(this.selectOptions,item.jsonKey,res.data)
                }
            })
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                this.tabUserList2.colum.forEach((item,index)=>{
                    if(item.type=='bfb'){
                        this.ruleForm[item.jsonKey] = this.ruleForm[item.jsonKey]+'%'
                    }
                })
                console.log(this.ruleForm)
                this.$emit('setTableValList',this.ruleForm)
            } else {
                return false;
            }
            });
        },
        editChangeVal(item){
            this.tabUserList2.colum.forEach((citem,index)=>{
                if(citem.type=='upload'){
                    this.filePath = item[citem.jsonKey]
                }
                if(citem.type=='bfb'){
                    this.$set(this.ruleForm,citem.jsonKey,item[citem.jsonKey].replace('%',''))
                }else{
                    this.$set(this.ruleForm,citem.jsonKey,item[citem.jsonKey])
                }
                
            })
        },
        getSelectFun(v,key){
            request({
                url: '/ht-bpmn/dic/selectPid?pid='+v,
                method: 'get',
                data:{}
            }).then((res) => {
                if(res.code==200){
                    this.$set(this.selectOptions,key,res.data)
                    sessionStorage.setItem('selectOptions',JSON.stringify(this.selectOptions))
                }
            })
        },

        // 保留小数位数
        formatDecimal(num, decimal) {
            num = num.toString()
            let index = num.indexOf('.')
            if (index !== -1) {
                num = num.substring(0, decimal + index + 1)
            } else {
                num = num.substring(0)
            }
            return parseFloat(num).toFixed(decimal)
        },
        handleRemove(file, fileList) {
            let vList = this.fileListArr.filter((item,index)=>{
                return item.path!=file.response.data
            })
            this.fileListArr = JSON.parse(JSON.stringify(vList))
        },
        handlePreview(file) {
          console.log(file)
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        closeFile(type){
            let a = JSON.parse(JSON.stringify(this.fileObjList))
            delete a[type]
            this.fileObjList = JSON.parse(JSON.stringify(a))
            this.fileListArr = this.fileListArr.filter((item)=>{return item.fileType!=type})
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除文件？`)
        },


        resetForm(formName) {
            this.ruleForm = {}
            // this.$refs[formName].resetFields();
        }
    }
  }
</script>

<style lang="scss" scoped>
.fileInfo{
    font-size: 10px;
    color: #999;
    position: absolute;
    top: 0px;
    left:90px;
    width: 160px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
     .autoClass{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }
      .autoClass .el-form-item{
        width:50%;
      }

</style>